package com.ant.myagile.backlog
import java.util.Map;

import com.ant.myagile.*
import grails.converters.JSON
import grails.converters.XML
import grails.plugins.springsecurity.Secured
import com.ant.myagile.TeamService;
import com.ant.myagile.dashboard.Status;

class IssueController {
	def springSecurityService
	def teamService
	
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
	IssueService issueService = new IssueService()
	
	def newIssue(){
				
	}
	
	def getProjectByUser(){
		def cUser = springSecurityService.currentUser
		def project = Project.findAllByOwner(cUser)
		def pro = Member.executeQuery("select a.id, a.lastName, a.firstName, b.team, c.project, d.projectName"
			+" from Member a, Team_Member b, Team_Project c, Project d where a.id = b.member and c.team = b.team and c.project = d.id and a.id ="+cUser.id);
		render ([project : project, pro : pro] as JSON)
	}
	
	def getUserStoryByProject(){
		def proId = params.proId
		def us = UserStory.executeQuery("select a.id, a.name from UserStory a where project="+proId)
		render ([us : us] as JSON)
	}
	
	def getAllTeams(){
		def cUser = springSecurityService.currentUser
		def team = teamService.getAllTeamByUser(cUser.id)
		render ([team : team] as JSON)
	}
	
	def getCurrentSprint(){		
		def sprint = Sprint.executeQuery("select id, sprintName from Sprint where team="+params.teamId+" order by dateStart desc",[max:1])
		render ([sprint : sprint] as JSON)
	}
	
	def getStatus(){
		def status = Status.executeQuery("select id, name from Status where sprint="+params.sprintId+" and team="+params.teamId)
		render ([status : status] as JSON)
	}
	
	def getMemberOfTeam(){
		def member = Member.executeQuery("select a.id, a.lastName, a.firstName, b.team "+
										"from Member a, Team_Member b "+
										"where a.id = b.member and b.team="+params.teamId)
		render ([member : member] as JSON)
	}
	
	def addIssue(){
		def issue = new Issue()
		issue.type = params.type
		issue.subject = params.subject
		issue.description = params.description
		issue.status = Status.get(params.status)
		if(params.assigned=="null"){
			issue.assigned = null
		}
		else {
		issue.assigned = Member.get(params.assigned)
		}
		issue.remain = params.remain
		issue.estimate = params.estimate
		issue.priority = params.priority
		issue.sprint = Sprint.findById(params.sprint)
		issue.userStory = UserStory.findById(params.userStory)
		issue.save(failOnError:true)
		[issue : issue]
		redirect(action: "newIssue", controller: "Issue")
	}
	
	//By tntho
	def jsonAddNewIssue(){
		def json = request.JSON
		def issue = new Issue()
		issue.type = json[0].type
		issue.subject = json[0].subject
		issue.description = json[0].description
		issue.status = Status.get(json[0].status)
		if(json[0].assigned=="null"){
			issue.assigned = null
		}
		else {
		issue.assigned = Member.get(json[0].assigned)
		}
		issue.remain = json[0].remain
		issue.estimate = json[0].estimate
		issue.priority = json[0].priority
		issue.sprint = Sprint.findById(json[0].sprint)
		issue.userStory = UserStory.findById(json[0].userStory)
		issue.save(failOnError:true)
		render ([newIssue: issue] as JSON)
	}
	
	def listIssue(){
		[issueList : Issue.list()]
	}
	
	def deleteIssue(){
		def iss = Issue.get(params.id)
		iss.delete()
		redirect(action:"listIssue", controller:"issue")
	}
	
	def editIssue(){
		def iss = Issue.get(params.id)
		[iss : iss , memberList : Member.list(), sprintList : Sprint.list(), userStoryList : UserStory.list()]
	}
	
	def updateIssue(){
		def issue = Issue.get(params.id)
		issue.type = params.type
		issue.subject = params.subject
		issue.description = params.description
		issue.status = params.status
		if(params.assigned=="null"){
			issue.assigned = null
		}
		else {
		issue.assigned = Member.get(params.assigned)
		}
		issue.remain = params.remain
		issue.estimate = params.estimate
		issue.priority = params.priority
		issue.sprint = Sprint.findById(params.sprint)
		issue.userStory = UserStory.findById(params.userStory)
		
		issue.save(failOnError:true)
		redirect(action: "listIssue", controller: "Issue")
	}
	
    def index() {
		redirect(action:"listIssue", controller:"Issue")

    }
	
	def testIssueImage(){
		[issue : Issue.list()]
	}
	
	def jsonFindIssueBySprint() {
		def sprintID = request.getParameter("sprintID");
		def issues = issueService.findIssueBySprintId(sprintID);
		if(issues) {
			render(contentType: 'text/json', {[issues : issues, result : 'OK']})
			response.status = 200
		} else {
			render(contentType: 'text/json', {[result : 'No Issue']})
			response.status = 200
		}
	}
	
	def ajaxAddNewIssue() {
		def sprintID = request.getParameter("sprintID");
		def userStoryID = request.getParameter("userStoryID");		
		Issue issue = issueService.addNewIssue(sprintID, userStoryID);
		if(issue) {
			render(contentType: 'text/json', {[issue : issue, result : 'OK']})
			response.status = 200
		} else {
			render(contentType: 'text/json', {[result : 'Failed']})
			response.status = 200
		}
	}

	def filterIssue() 
	{
		Hashtable<String, String> ht= new Hashtable<String, String>()
		if(params.filter!="None")
			ht.put("i.status", params.filter)
		def issues= issueService.SearchIssue(ht)
		def html=""
		if(issues)
		{
			for ( data in issues ) 
			{
				def assign
				if(data.assigned)
					assign=data.assigned.firstName+" "+data.assigned.lastName
				else
					assign=""
				
				html+="<tr>"
				html+="<td>"+data.id+"</td>"
				html+="<td>"+data.type+"</td>"
				html+="<td>"+data.subject+"</td>"
				html+="<td>"+data.description+"</td>"
				html+="<td>"+data.status+"</td>"
				html+="<td>"+data.priority+"</td>"
				html+="<td>"+assign+"</td>"
				html+="<td>"+data.remain+"</td>"
				html+="<td>"+data.estimate+"</td>"
				
				html+="<td>"+data.userStory.description+"</td>"
				html+="<td>"+data.sprint.sprintName+"</td>"
				html+="<td>"
				html+="	<form action='deleteIssue' controller='issue' style='margin:0'>"
				html+="	<input type='hidden' name='id' value="+data.id+">"
				html+="<input id='submit' class='btn' type='submit' onclick=\"return confirm('Are you sure?');\" name='submit' value='Delete'>"
				html+="	</form>"
				html+="</td>"
				html+="<td>"
				html+="	<a href='editIssue?id="+data.id+"' class='btn'>Edit</a>"
				html+="</td>"
				html+="</tr>"
			}
		}
		render html
	}
	
	def filterIssueReport()
	{
		Hashtable<String, String> ht= new Hashtable<String, String>()
		if(params.h_status!="None")
			ht.put("i.status", params.h_status)
		def issues= issueService.SearchIssue(ht)

		if(issues.size()==0)
			chain(controller:'jasper',action:'index',model:[data:null],params:params)
		else
			chain(controller:'jasper',action:'index',model:[data:issues],params:params)
	}

}
